<?php
set_time_limit(300);
defined('IN_PHPCMS') or exit('No permission resources.');
// 模型缓存路径
define('CACHE_MODEL_PATH', CACHE_PATH . 'caches_model' . DIRECTORY_SEPARATOR . 'caches_data' . DIRECTORY_SEPARATOR);
// 定义在单独操作内容的时候，同时更新相关栏目页面
define('RELATION_HTML', true);

pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('util');
pc_base::load_sys_class('format', '', 0);

/**
 * 图片管理
 */
class file extends admin
{
    public $siteid;
    public $path_file,$path_url;

    public function __construct()
    {
        parent::__construct();
        pc_base::load_app_func('global');
        $this->path_file = str_replace('/images/','',pc_base::load_config('system','upload_path'));
        $this->path_url = str_replace('/images/','',pc_base::load_config('system','upload_url'));
        $this->siteid = get_siteid();
    }

    /**
     * 文件列表
     */
    public function index()
    {
        $dir = trim($_GET['dir']) ? str_replace(array('..\\', '../', './', '.\\'), '', trim($_GET['dir'])) : '';
        $filepath = $this->path_file.'/statics/' . (($dir != '' && $dir != '.')?$dir.'/':'');
        $list = glob($filepath.'/'.'*');
        if(!empty($list)) rsort($list);
        $local = str_replace(array(PC_PATH, $this->path_file ,DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR), array('','',DIRECTORY_SEPARATOR), $filepath);
        //$show_header = true;
        $lists = array();
        foreach ($list as $k => $v) {
            $lists[$k]['filepath'] = $v;
            $filestat = stat($v);
            $lists[$k]['filename'] = basename($v);
            $lists[$k]['filetime'] = $filestat['atime'];
            if (!is_dir($v)) {
                $lists[$k]['filesize'] = sizecount($filestat['size']);
                $lists[$k]['filetype'] = '文件';
                $lists[$k]['status'] = 1;
                $lists[$k]['url'] = $this->path_url.(str_replace('/public','',$local)).basename($v);
            } else {
                $lists[$k]['url'] = '?m=attachment&c=file&a=index&dir='.(($dir) ? stripslashes($dir).'/' : '').basename($v);
                $lists[$k]['filesize'] = '目录';
                $lists[$k]['filetype'] = '文件夹';
                $lists[$k]['status'] = 0;
            }
        }
        $big_menu0 = 'javascript:window.top.art.dialog({id:\'adddir\',iframe:\'?m=attachment&c=file&a=adddir&dir='.$dir.'\', title:\''.L('adddir').'\', width:\'700\', height:\'150\'}, function(){var d = window.top.art.dialog({id:\'adddir\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'adddir\'}).close()});void(0);';
        $big_menu1 = 'javascript:window.top.art.dialog({id:\'addfile\',iframe:\'?m=attachment&c=file&a=addfile&dir='.$dir.'\', title:\''.L('addfile').'\', width:\'900\', height:\'350\'}, function(){window.top.art.dialog({id:\'addfile\'}).close();location.reload();});void(0);';
        include $this->admin_tpl('file_list');
    }

    /**
     * 新建目录
     */
    public function adddir ()
    {
        $dir = trim($_GET['dir']) ? str_replace(array('..\\', '../', './', '.\\'), '', trim($_GET['dir'])) : '';
        if(isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $filepath = $this->path_file.'/statics/' . (($dir != '' && $dir != '.')?$dir.'/':'');
            $dirname = trim($_POST['dirname']);
            if (!$dirname) {
                showmessage('目录地址不能为空', HTTP_REFERER);
            }
            $path = $filepath . $dirname;
            if (is_dir($path)){
                showmessage("对不起！目录 " . $path . " 已经存在！", HTTP_REFERER);
            }else{
                //第三个参数是“true”表示能创建多级目录
                $res = mkdir($path,0777,true);
                @chmod($path, 0777);
                if ($res){
                    showmessage(L('operation_success'), HTTP_REFERER, '', 'adddir');
                }else{
                    showmessage(L('operation_failure'), HTTP_REFERER);
                }
            }
        } else {  
            include $this->admin_tpl('adddir');
        }
    }

    /**
     * 上传文件
     */
    public function addFile ()
    {
        $up = pc_base::load_sys_class('FileUpload', '', 1);
        $dir = trim($_GET['dir']) ? str_replace(array('..\\', '../', './', '.\\'), '', trim($_GET['dir'])) : '';;
        $filepath = $this->path_file.'/statics/' . (($dir != '' && $dir != '.')?$dir.'/':'');
        if(isset($_GET['dosubmit']) && ! empty($_GET['dosubmit'])) {
            //设置属性(上传的位置， 大小， 类型， 名是是否要随机生成)
            $up -> set('path', $filepath);
            $up -> set("maxsize", 2000000);
            $up -> set("allowtype", array("gif", "png", "jpg", "jpeg", "js", "css"));
            $up -> set("israndname", false);

            if ($up -> upload("Filedata")) {
                $fileName=$up->getFileName();
                echo '1002,上传成功';die;
            } else {
                echo '1003,出错';die;
            }
        } else {
            $pc_hash = $_GET['pc_hash'];
            include $this->admin_tpl('addfile');
        }
    }

    /**
     * 删除文件、目录
     */
    public function delFile ()
    {
        $data['status'] = 0;
        $data['info'] = '';
        $data['content'] = '';
        $dir = trim($_POST['dir']) ? str_replace(array('..\\', '../', './', '.\\'), '', trim($_POST['dir'])) : '';
        $filepath = $this->path_file.'/statics/' . (($dir != '' && $dir != '.')?$dir.'/':'');
        $filename = $_POST['filename']?trim($_POST['filename']):'';
        if (!$filename) {
            $data['status'] = 0;
            $data['info'] = '删除的文件或目录不存在';
        }
        $path = $filepath.$filename;
        if (is_dir($path)) {
            $list = glob($path.'/'.'*');
            if (empty($list)) {
                $status = rmdir($path);
                if ($status) {
                    $data['status'] = 1;
                    $data['info'] = '删除成功';
                } else {
                    $data['status'] = 0;
                    $data['info'] = '删除失败';
                }
            } else {
                $data['status'] = 0;
                $data['info'] = '该目录有文件，不能删除';
            }
        } else {
            $status = unlink($path);
            if ($status) {
                $data['status'] = 1;
                $data['info'] = '删除成功';
            } else {
                $data['status'] = 0;
                $data['info'] = '删除失败';
            }
        }
        echo json_encode($data);die;
    }

    /**
     * 批量删除文件、目录
     */
    public function delAll ()
    {
        $dir = trim($_GET['dir']) ? str_replace(array('..\\', '../', './', '.\\'), '', trim($_GET['dir'])) : '';
        $filepath = $this->path_file.'/statics/' . (($dir != '' && $dir != '.')?$dir.'/':'');
        $fileNames = $_POST['fileNames'];
        foreach ($fileNames as $fileName) {
            $filename = trim($fileName);
            if (!$filename) {
                showmessage('删除的文件或目录不存在', HTTP_REFERER);
            }
            $path = $filepath.$filename;
            if (is_dir($path)) {
                $list = glob($path.'/'.'*');
                if (empty($list)) {
                    $status = rmdir($path);
                    if (!$status) {
                        showmessage(L('operation_failure'), HTTP_REFERER);    
                    }
                } else {
                    showmessage('该目录有文件，不能删除', HTTP_REFERER);
                }
            } else {
                $status = unlink($path);
                if (!$status) {
                    showmessage(L('operation_failure'), HTTP_REFERER);
                }
            }
        }
        showmessage(L('operation_success'), HTTP_REFERER);
    }
}